import { defineStore } from 'pinia'
import { store } from '../index'
import { UserLoginType, UserType, UserInfo } from '@/api/login/types'
import {ElMessage, ElMessageBox} from 'element-plus'
import { useI18n } from '@/hooks/web/useI18n'
// import { loginOutApi } from '@/api/login'
import { useTagsViewStore } from './tagsView'
import router from '@/router'
import { getInfoApi, logoutApi } from '@/api/auth'
import { usePermissionStoreWithOut } from './permission'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { ssoLoginApi } from '@/api/auth'
import {push} from "echarts/types/src/component/dataZoom/history";
import {useRouter} from "vue-router";

interface UserState {
  userInfo?: UserType
  tokenKey: string
  token: string
  roleRouters?: string[] | AppCustomRouteRecordRaw[]
  rememberMe: boolean
  loginInfo?: UserLoginType
  roles: string[]
  perms: string[]
  roleTypes: string[]
}

export const useUserStore = defineStore('user', {
  state: (): UserState => {
    return {
      userInfo: undefined,
      tokenKey: 'Authorization',
      token: '',
      roleRouters: undefined,
      // 记住我
      rememberMe: true,
      loginInfo: undefined,
      roles: [],
      perms: [],
      roleTypes: []
    }
  },
  getters: {
    getTokenKey(): string {
      return this.tokenKey
    },
    getToken(): string {
      return this.token
    },
    getUserInfo(): UserType | undefined {
      return this.userInfo
    },
    getRoleRouters(): string[] | AppCustomRouteRecordRaw[] | undefined {
      return this.roleRouters
    },
    getRememberMe(): boolean {
      return this.rememberMe
    },
    getLoginInfo(): UserLoginType | undefined {
      return this.loginInfo
    },
    getRoles(): string[] {
      return this.roles
    }
  },
  actions: {
    setTokenKey(tokenKey: string) {
      this.tokenKey = tokenKey
    },
    setToken(token: string) {
      this.token = token
      setToken(this.token)
    },
    setUserInfo(userInfo?: UserType) {
      this.userInfo = userInfo
    },
    setRoleRouters(roleRouters: string[] | AppCustomRouteRecordRaw[]) {
      this.roleRouters = roleRouters
    },
    logoutConfirm() {
      const { t } = useI18n()
      ElMessageBox.confirm(t('common.loginOutMessage'), t('common.reminder'), {
        confirmButtonText: t('common.ok'),
        cancelButtonText: t('common.cancel'),
        type: 'warning'
      })
        .then(async () => {
          const res = await logoutApi().catch(() => {})
          if (res) {
            this.reset()
          }
        })
        .catch(() => {})
    },
    reset() {
      const tagsViewStore = useTagsViewStore()
      const permissionStore = usePermissionStoreWithOut()
      tagsViewStore.delAllViews()
      removeToken()
      this.setUserInfo(undefined)
      this.setRoleRouters([])
      this.resetRoles()
      permissionStore.setIsAddRouters(false)
      router.replace('/login')
    },
    resetRoles() {
      this.roles = []
      this.perms = []
      this.roleTypes = []
    },
    logout() {
      return new Promise<void>(() => {
        logoutApi().then(() => {
          this.reset()
        })
      })
    },
    setRememberMe(rememberMe: boolean) {
      this.rememberMe = rememberMe
    },
    setLoginInfo(loginInfo: UserLoginType | undefined) {
      this.loginInfo = loginInfo
    },
    // 获取信息(用户昵称、头像、角色集合、权限集合)
    getInfo() {
      return new Promise<UserInfo>((resolve, reject) => {
        getInfoApi()
          .then((res) => {
            if (!res || !res.data) {
              return reject('获取用户信息失败，请重新登录')
            }


            // 判断是否需要强制修改密码
            if (res.data.user.mustUpdatePwd === 'Y'){
              ElMessage({
                message: '请更新密码',
                type: 'warning',
              })
              router.replace('/resetPassword')
            }
            // 判断密码是否快要过期：在需要修改密码前七天内
            if (res.data.user.updatePwdTime !== null &&  isWithinSevenDays(res.data.user.updatePwdTime)){
              ElMessage({
                message: '密码将在7天内过期，请修改及时密码',
                type: 'warning',
              })
            }

            this.roles = (res.data.roles && res.data.roles.length) ? res.data.roles : []
            this.perms = (res.data.permissions && res.data.permissions.length) ? res.data.permissions : []
            this.roleTypes = (res.data.roleTypes && res.data.roleTypes.length) ? res.data.roleTypes : []
            this.userInfo = res.data.user
            // avatar.value = (user.avatar && import.meta.env.VITE_APP_BASE_API + user.avatar) || require("@/assets/image/profile.jpg");
            resolve(res.data)
          })
          .catch((error) => {
            console.error('getInfoApi error:', error)
            reject(error)
          })
      })
    },
    async autoSsoLogin(token: string) {
      return ssoLoginApi(token)
        .then((res) => {
          setToken(res.data)
          this.getInfo()
        })
        .catch((e) => {
          // 登录失败，提示错误
          console.log('登录授权失败：Token不合法')
        })
    }
  },
  persist: false
})

export const useUserStoreWithOut = () => {
  return useUserStore(store)
}

// 判断密码是否在7天内过期
function isWithinSevenDays(timeString: string): boolean {
  const updatePwdDate = new Date(timeString);
  const currentDate = new Date();
  const diffTime = Math.abs((currentDate as any) - (updatePwdDate as any));
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

  return diffDays <= 7;
}
